package dabs.engine.plant;

import java.io.Serializable;
import java.util.ArrayList;

public class HydraulicState implements Serializable {
	private static final long serialVersionUID = -7872945509964016537L;
	
	private final int base = 20;
	private int waterLevel;
	private int steamLevel;
	
	public int getWaterLevel() { return waterLevel; }
	public int getSteamLevel() { return steamLevel; }
	
	public void receive(int levelChange, boolean steamToWater) {
		if (steamToWater) {
			waterLevel += levelChange;
		}
		else {
			steamLevel += levelChange;
		}
	}
	
	public void update(double modifier, boolean steamToWater, ArrayList<ComponentPart> outputs) {
		int levelChange = (int) (base * modifier);

		if (steamToWater) {
			levelChange = getLevelChange(levelChange, steamLevel);
			waterLevel += levelChange;
			steamLevel -= levelChange;
		}
		else {
			levelChange = getLevelChange(levelChange, waterLevel);
			steamLevel += levelChange;
			waterLevel -= levelChange;
		}
		sendToNext((int)(base * 0.5), steamToWater, outputs);
	}
	public void sendToNext(int levelChange, boolean steamToWater, ArrayList<ComponentPart> outputs) {
		int count = outputs.size();
		if (steamToWater) {
			levelChange = getLevelChange(levelChange, waterLevel);
			waterLevel -= levelChange;
		}
		else {
			levelChange = getLevelChange(levelChange, steamLevel);
			steamLevel -= levelChange;
		}
		if (count == 1) outputs.get(0).getNewHydroState().receive(levelChange, steamToWater);
		if (count == 2) {
			outputs.get(0).getNewHydroState().receive(levelChange/2, steamToWater);
			levelChange -= levelChange / 2;
			outputs.get(1).getNewHydroState().receive(levelChange, steamToWater);
		}
	}
	public int getLevelChange(int levelChange, int unit) {
		if (unit <= levelChange) {
			return unit;
		}
		else {
			return levelChange;
		}
	}
	
	public String toString() {
		return String.format("water: %d, steam: %d", waterLevel, steamLevel); 
	}
}
